package com.dennytech.tac.widget;

import java.util.List;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dennytech.tac.R;
import com.dennytech.tac.model.Channel;
import com.dennytech.tac.utils.db.ChannelDBHelper;

public class ChannelListItem extends LinearLayout {

	private TextView title;
	private ImageView add;
	private Channel channel;

	private static final int CHANNEL_STATUS_UNINIT = -1;
	private static final int CHANNEL_STATUS_NOT_ADDED = 0;
	private static final int CHANNEL_STATUS_ADDED = 1;

	int channelStatus = CHANNEL_STATUS_UNINIT;

	public ChannelListItem(Context context) {
		super(context);
	}

	public ChannelListItem(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();
		title = (TextView) findViewById(R.id.title);
		add = (ImageView) findViewById(R.id.add);
	}

	public void setChannel(Channel c) {
		channel = c;
		title.setText(c.getName());
		channelStatus = isChannelAdded(c) ? CHANNEL_STATUS_ADDED
				: CHANNEL_STATUS_NOT_ADDED;
		resetAddIcon();
	}

	private void resetAddIcon() {
		if (channelStatus == CHANNEL_STATUS_ADDED) {
			add.setImageResource(R.drawable.ic_channel_success);
		} else {
			add.setImageResource(R.drawable.ic_channel_add);
		}
	}

	public void changeChannelStatus() {
		channelStatus = (channelStatus + 1) % 2;

		resetAddIcon();
		if (channel != null) {
			ChannelDBHelper dbHelper = ChannelDBHelper.instance();
			if (channelStatus == CHANNEL_STATUS_ADDED) {
				dbHelper.insert(channel);
			} else {
				dbHelper.delete(channel);
			}
		}
	}

	// 本地数据里做对比，检查是否已经添加该channel
	// TODO 未来可以优化，做缓存，不要每次从数据库取
	
	private boolean isChannelAdded(Channel c) {
		if (channelStatus > CHANNEL_STATUS_UNINIT) {
			return channelStatus == CHANNEL_STATUS_ADDED;
		}

		List<Channel> list = ChannelDBHelper.instance().query();
		if (list == null) {
			return false;
		}
		
		for (Channel channel : list) {
			if (c.getId() == channel.getId()) {
				return true;
			}
		}

		return false;
	}

}
